package com.qingfeng.client.api;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qingfeng.base.model.Page;
import com.qingfeng.client.VO.OrderExcelVo;
import com.qingfeng.client.bean.*;
import com.qingfeng.client.dao.OrderGoodsMapper;
import com.qingfeng.client.dao.OrderStoreMapper;
import com.qingfeng.client.service.TradeService;
import com.qingfeng.util.ExcelMergeStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author ff
 * @Data 2017/11/6 16:09
 */
@Api(tags = "交易")
@Controller
@RequestMapping(value = "/api/trade")
public class TradeApi extends BaseV1Api{

    @Resource
    private TradeService tradeService;

    @Resource
    private OrderStoreMapper orderStoreDao;

    @Resource
    private OrderGoodsMapper orderGoodsDao;

    @Autowired
    private OrderStoreMapper orderStoreMapper;

    @ApiOperation("导出所有订单")
    @GetMapping(value = "/exportList")
    public void exportList(HttpServletResponse response) throws IOException {
        Seller seller = getUser();
        List<OrderExcelVo> list = orderStoreDao.selectOrderInfo(seller.getStoreId());
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Integer> indexs = new ArrayList<>();
            ExcelMergeStrategy excelMergeStrategy = new ExcelMergeStrategy(list);
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), OrderExcelVo.class)
                    .sheet("订单")
                    .registerWriteHandler(excelMergeStrategy)
                    .doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(error("下载失败").toJSONString());
        }
    }


    @ResponseBody
    @ApiOperation("获取交易列表")
    @PostMapping(value = "/list")
    public Object getAll(@RequestBody JSONObject jsonObject){
        Seller sellerBean = getUser();
        Page page = parsePageJSON(jsonObject.getJSONObject("page"));
        OrderStore orderStoreBean = JSON.toJavaObject(jsonObject.getJSONObject("item"),OrderStore.class);
        Integer storeId = sellerBean.getStoreId();
        if (storeId==null){
            return error(null);
        }
        orderStoreBean.setStoreId(storeId);
        IPage page1 = orderStoreDao.getPageList(page,orderStoreBean);
        return successPage(page1);
    }


    @ResponseBody
    @ApiOperation("获取交易详情")
    @GetMapping(value = "/getDetail/{id}")
    public Object getDetail(@PathVariable(value = "id") Long orderStoreId){
        JSONObject jsonObject = tradeService.getDetail(orderStoreId);
        return jsonObject;
    }


    /**
     * 发货
     * @param jsonObject，id，logisticsCode，comment
     * @return
     */
    @ResponseBody
    @ApiOperation("发货")
    @PostMapping(value = "/sendGoods")
    public Object sendGoods(@RequestBody JSONObject jsonObject){
        Seller sellerBean = getUser();
        Logistics logisticsBean = JSON.toJavaObject(jsonObject.getJSONObject("logistics"),Logistics.class);
        Long orderStoreId = jsonObject.getLong("id");
        List<OrderGoods> list = orderGoodsDao.selectByOrderStoreId(orderStoreId,sellerBean.getStoreId());
        if (list.size()==0){
            return error("该笔订单不存在");
        }
        for (OrderGoods orderGoodsBean:list){
            if (orderGoodsBean.getStat()==-1){
                return error("该笔订单存在退款,请查看详情");
            }
        }
        if(tradeService.sendGoods(logisticsBean,orderStoreId,sellerBean.getStoreId(),sellerBean.getId())){
            return success(null);
        }else {
            return error(null);
        }
    }

    @ResponseBody
    @ApiOperation("更新交易信息")
    @PostMapping(value = "/update")
    public Object update(@RequestBody Trade tradeBean){
        if (tradeService.update(tradeBean)){
            return success(null);
        }else {
            return error(null);
        }
    }



}
